{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Anaconda 默认不包含 docx工具包，需要执行以下脚本进行安装\n",
    "# 如果本地没有安装工具包，请去掉“#”，再执行\n",
    "# !pip install -i https://mirrors.aliyun.com/pypi/simple/ python-docx"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 1、导入包并创建一个 Word 文档对象"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import docx\n",
    "# 从docx 工具包中导入要使用的对象\n",
    "from docx import Document\n",
    "# 字号、尺寸、大小单位：pt(点数或磅)、inch(英寸)、cm(厘米)等等\n",
    "from docx.shared import Pt,Inches, Cm\n",
    "# 文本相关段落对齐\n",
    "from docx.enum.text import WD_PARAGRAPH_ALIGNMENT\n",
    "# 表格相关的对齐\n",
    "from docx.enum.table import WD_TABLE_ALIGNMENT,WD_ALIGN_VERTICAL\n",
    "# RGB 颜色，用于字体颜色\n",
    "from docx.shared import RGBColor \n",
    "# 标准预设颜色。用于字体突出显示背景色 （默认为 AUTO 自动上色，通常为黑色）\n",
    "from docx.enum.text import WD_COLOR_INDEX\n",
    "\n",
    "# Document 不包含文件路径就是在内存中创建 Word 对象\n",
    "document = Document()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 2、知识点（类型转换）"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 类型转换的作用"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "num1 = \"1\" # 字符串类型\n",
    "num2 = \"2\" # 字符串类型\n",
    "# 我们想计算 1 + 2 = 3 的功能\n",
    "print(\"字符串：1 + 2 =\", num1 + num2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "num1 = int(num1) # 类型转换为整型（整数）\n",
    "num2 = int(num2) # 类型转换为整型（整数）\n",
    "print(\"整数型：1 + 2 =\", num1 + num2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 其他类型转换样例"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 数据类型的转换\n",
    "# num 是一个整型数（整数）\n",
    "num = 123\n",
    "# 通过 str 函数的转换为字符串类型（文本） \n",
    "str_num = str(num)\n",
    "# 通过 float 函数的转换为浮点型类型（小数） \n",
    "f_num = float(str_num)\n",
    "# 通过 int 函数的转换为整型类型（整数） \n",
    "int_num = int(str_num)\n",
    "\n",
    "print(\"num 的类型为：%s；num + num = %s\" % (type(num) , (num+num)))\n",
    "print(\"str_num 的类型为：%s；str_num + str_num = %s\" % (type(str_num) , (str_num+str_num)))\n",
    "print(\"f_num 的类型为：%s；f_num + f_num = %s\" % (type(f_num) , (f_num+f_num)))\n",
    "print(\"int_num 的类型为：%s；int_num + int_num = %s\" % (type(int_num) , (int_num+int_num)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 3、使用WORD默认表格样式"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.1 创建表格的函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 该函数为 03.Word表格图片 课程中思考题答案，增加了行高、列宽、布局的控制代码\n",
    "def create_table(data_list):\n",
    "    \"\"\"\n",
    "    使用方法：create_table(data_list)\n",
    "    :param data_list: 数据列表（列表中的列表，第一行是列名）\n",
    "    :return: table\n",
    "    \"\"\"\n",
    "    # 取第一行的列名\n",
    "    col_names = data_list[0]\n",
    "    # 增加一个表格，有 0 行 len(col_names) 列\n",
    "    new_table = document.add_table(rows=0, cols=len(col_names))\n",
    "    \n",
    "    # 表格的对齐方式：\n",
    "    \"\"\"\n",
    "    WD_TABLE_ALIGNMENT.LEFT ：表格为左对齐\n",
    "    WD_TABLE_ALIGNMENT.CENTER：表格为居中对齐\n",
    "    WD_TABLE_ALIGNMENT.RIGHT：表格为右对齐\n",
    "    \"\"\"\n",
    "    new_table.alignment = WD_TABLE_ALIGNMENT.CENTER\n",
    "\n",
    "    # 循环遍历 data_list 列表\n",
    "    for row_index, item in enumerate(data_list):\n",
    "        # 增加一行\n",
    "        new_row = new_table.add_row()\n",
    "         # 使用厘米单位设置行高 \n",
    "        new_row.height = Cm(1) # Inches(0.5) # 使用英寸单位\n",
    "        # 并获取单元格列表\n",
    "        new_cells = new_row.cells\n",
    "        # 循环遍历列索引\n",
    "        for col_index, col_name in enumerate(col_names):\n",
    "            # 写入每列的数据，\n",
    "            # 因为 text 属性只接受字符串类型，所以需要使用函数str进行**类型转换**\n",
    "            new_cells[col_index].text = str(item[col_index])\n",
    "            \n",
    "            # 单元格垂直居中\n",
    "            \"\"\"\n",
    "            WD_ALIGN_VERTICAL.TOP 文本与单元格的上边框对齐。\n",
    "            WD_ALIGN_VERTICAL.CENTER 文本与单元格的中心对齐。\n",
    "            WD_ALIGN_VERTICAL.BOTTOM 文本与单元格的下边框对齐。\n",
    "            \"\"\"            \n",
    "            new_cells[col_index].vertical_alignment = WD_ALIGN_VERTICAL.CENTER\n",
    "            # 单元格第一个段落内容居中（可以存在多个段落，并可以设置各自的对齐方式）            \n",
    "            new_cells[col_index].paragraphs[0].paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER\n",
    "            # 可以删除掉下面代码的注释看看各个段落的对齐方式\n",
    "            # new_cells[col_index].add_paragraph(\"段落左对齐\").paragraph_format.alignment = WD_TABLE_ALIGNMENT.LEFT\n",
    "            # new_cells[col_index].add_paragraph(\"段落右对齐\").paragraph_format.alignment = WD_TABLE_ALIGNMENT.RIGHT\n",
    "\n",
    "    return new_table"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.2 创建设置表格列宽的函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 设置表格列宽的函数\n",
    "def set_col_widths(table, widths):\n",
    "    \"\"\"\n",
    "    设置每列的宽度。\n",
    "    使用方法：set_col_widths(table, [Inches(1), Inches(2), Inches(7)])\n",
    "    \n",
    "    :param table: 表格对象\n",
    "    :param widths: 列宽列表或者元组\n",
    "    \"\"\"\n",
    "    # 为了代码的严谨，这里做了一个判断，如果表格的行数为0，则无法设置宽度。\n",
    "    # 如果没有这个判断代码，则取表格的第一行代码就会报错\n",
    "    if len(table.rows) == 0:\n",
    "        return\n",
    "    # 取表格的第一行，设置该行单元格的宽度\n",
    "    row = table.rows[0]\n",
    "    for idx, width in enumerate(widths):\n",
    "        row.cells[idx].width = width"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#  widths 长度大小单位展示的数值对比\n",
    "Inches(1), Cm(1), Pt(1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.3 创建指定样式表格的函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 创建带有样式的表格函数，参数为表格样式名\n",
    "# style 参考课程结尾提供的“WORD 默认模板中的样式：表格样式”\n",
    "def create_table_with_style(style):\n",
    "    # 添加一级标题\n",
    "    document.add_heading('表格样式：'+style, level=2)\n",
    "    # 这里使用了元组(和列表用法类似，暂不展开讲解，大家了解一下)\n",
    "    data_list = (\n",
    "        ('序号', '对象', '说明'),\n",
    "        (1, 'Document', '表示整个文档'),\n",
    "        (2, 'Paragraph', '表示段落（每一次回车会产生新段落）'),\n",
    "        (3, 'Run', '表示相同样式的文本延续')\n",
    "    )\n",
    "    # 创建表格\n",
    "    table = create_table(data_list)\n",
    "    # 指定表格的样式\n",
    "    table.style = style\n",
    "\n",
    "    # 注意这里的列宽加起来需要等于10（1+2+7），因为word会自动调整列宽\n",
    "    widths = [Inches(1), Inches(2), Inches(7)]\n",
    "    # 设置表格的列宽\n",
    "    set_col_widths(table, widths)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# style 参考课程结尾提供的“WORD 默认模板中的样式：表格样式”\n",
    "create_table_with_style(\"Light List Accent 2\")\n",
    "create_table_with_style(\"Light Shading Accent 1\")\n",
    "create_table_with_style(\"Medium Grid 3 Accent 1\")\n",
    "\n",
    "save_file = r'.\\files\\Word_表格样式.docx'\n",
    "# 保存内存中的document对象到文件\n",
    "document.save(save_file)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 思考题"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 通过循环把下面所有样式都创建一个表格，并保存到一个Word文档\n",
    "\n",
    "\n",
    "* 提示：\n",
    "```\n",
    "for ....\n",
    "   create_table_with_style(style=表格样式)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# WORD 默认模板中的样式"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<table width=\"100%\" border=\"0\">\n",
    "<tr>\n",
    " \n",
    "  <td valign=\"top\" width=\"100%\" style=\"vertical-align:top; text-align:left;background-color:#ddffdd\">\n",
    "      \n",
    "   <font color=\"blue\" size=\"3px\"> 表格样式</font>\n",
    "\n",
    "\n",
    "<table width=\"100%\" border=\"0\">\n",
    "<tr>\n",
    "    <td valign=\"top\" width=\"30%\" style=\"vertical-align:top; text-align:left;background-color:#ddffdd\">\n",
    "\n",
    "* Colorful Grid\n",
    "* Colorful Grid Accent 1\n",
    "* Colorful Grid Accent 2\n",
    "* Colorful Grid Accent 3\n",
    "* Colorful Grid Accent 4\n",
    "* Colorful Grid Accent 5\n",
    "* Colorful Grid Accent 6\n",
    "* Colorful List\n",
    "* Colorful List Accent 1\n",
    "* Colorful List Accent 2\n",
    "* Colorful List Accent 3\n",
    "* Colorful List Accent 4\n",
    "* Colorful List Accent 5\n",
    "* Colorful List Accent 6\n",
    "* Colorful Shading\n",
    "* Colorful Shading Accent 1\n",
    "* Colorful Shading Accent 2\n",
    "* Colorful Shading Accent 3\n",
    "* Colorful Shading Accent 4\n",
    "* Colorful Shading Accent 5\n",
    "* Colorful Shading Accent 6\n",
    "* Dark List\n",
    "* Dark List Accent 1\n",
    "* Dark List Accent 2\n",
    "* Dark List Accent 3\n",
    "* Dark List Accent 4\n",
    "* Dark List Accent 5\n",
    "* Dark List Accent 6\n",
    "* Light Grid\n",
    "* Light Grid Accent 1\n",
    "* Light Grid Accent 2\n",
    "* Light Grid Accent 3\n",
    "* Light Grid Accent 4\n",
    "* Light Grid Accent 5\n",
    "* Light Grid Accent 6    \n",
    "        \n",
    "        \n",
    "</td>\n",
    "    \n",
    "<td width=\"30%\" style=\"vertical-align:top; text-align:left;background-color:#ddffdd\">\n",
    "        \n",
    "* Light List\n",
    "* Light List Accent 1\n",
    "* Light List Accent 2\n",
    "* Light List Accent 3\n",
    "* Light List Accent 4\n",
    "* Light List Accent 5\n",
    "* Light List Accent 6\n",
    "* Light Shading\n",
    "* Light Shading Accent 1\n",
    "* Light Shading Accent 2\n",
    "* Light Shading Accent 3\n",
    "* Light Shading Accent 4\n",
    "* Light Shading Accent 5\n",
    "* Light Shading Accent 6\n",
    "* Medium Grid 1\n",
    "* Medium Grid 1 Accent 1\n",
    "* Medium Grid 1 Accent 2\n",
    "* Medium Grid 1 Accent 3\n",
    "* Medium Grid 1 Accent 4\n",
    "* Medium Grid 1 Accent 5\n",
    "* Medium Grid 1 Accent 6\n",
    "* Medium Grid 2\n",
    "* Medium Grid 2 Accent 1\n",
    "* Medium Grid 2 Accent 2\n",
    "* Medium Grid 2 Accent 3\n",
    "* Medium Grid 2 Accent 4\n",
    "* Medium Grid 2 Accent 5\n",
    "* Medium Grid 2 Accent 6\n",
    "* Medium Grid 3\n",
    "* Medium Grid 3 Accent 1\n",
    "* Medium Grid 3 Accent 2\n",
    "* Medium Grid 3 Accent 3\n",
    "* Medium Grid 3 Accent 4\n",
    "* Medium Grid 3 Accent 5\n",
    "* Medium Grid 3 Accent 6\n",
    "        \n",
    "</td>   \n",
    "    \n",
    "<td valign=\"top\" width=\"30%\" style=\"vertical-align:top; text-align:left;background-color:#ddffdd\">\n",
    "  \n",
    "* Medium List 1\n",
    "* Medium List 1 Accent 1\n",
    "* Medium List 1 Accent 2\n",
    "* Medium List 1 Accent 3\n",
    "* Medium List 1 Accent 4\n",
    "* Medium List 1 Accent 5\n",
    "* Medium List 1 Accent 6\n",
    "* Medium List 2\n",
    "* Medium List 2 Accent 1\n",
    "* Medium List 2 Accent 2\n",
    "* Medium List 2 Accent 3\n",
    "* Medium List 2 Accent 4\n",
    "* Medium List 2 Accent 5\n",
    "* Medium List 2 Accent 6\n",
    "* Medium Shading 1\n",
    "* Medium Shading 1 Accent 1\n",
    "* Medium Shading 1 Accent 2\n",
    "* Medium Shading 1 Accent 3\n",
    "* Medium Shading 1 Accent 4\n",
    "* Medium Shading 1 Accent 5\n",
    "* Medium Shading 1 Accent 6\n",
    "* Medium Shading 2\n",
    "* Medium Shading 2 Accent 1\n",
    "* Medium Shading 2 Accent 2\n",
    "* Medium Shading 2 Accent 3\n",
    "* Medium Shading 2 Accent 4\n",
    "* Medium Shading 2 Accent 5\n",
    "* Medium Shading 2 Accent 6\n",
    "* Table Grid\n",
    " \n",
    "</td>  \n",
    "</tr>\n",
    "\n",
    "</table>\n",
    "\n",
    "\n",
    "\n",
    "  </td>\n",
    " </tr>\n",
    "\n",
    "</table>\n",
    "\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
